<template>
<el-card class="box-card" style="width: 1180px">
  <!-- --------------------------------搜索---------------------------------------- -->
  <div slot="header" class="clearfix">
      <el-form :inline="true" :model="query">
        <!-- 根据名字查询 -->
        <el-form-item>
          <el-input
            v-model="query.name"
            placeholder="姓名"
            :clearable="true"
          ></el-input>
        </el-form-item>
         <!-- 根据时间查询 -->
         <el-form-item>
          <el-date-picker
            v-model="query.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始注册日期"
            end-placeholder="结束注册日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="loadUsers()">
            <i class="el-icon-search"></i>
            </el-button> 
             <el-button type="success" @click="dialog.addshow = true">添加</el-button>  
             <el-button type="success" @click="exportExcel">导出数据</el-button>
        </el-form-item> -->
        <el-form-item>
    <el-row>
          <el-col :span="20">
                   <el-button type="primary" @click="loadUsers()">
            <i class="el-icon-search"></i>
            </el-button> 
             <el-button type="success" @click="dialog.addshow = true">添加</el-button>  
             <el-button type="success" @click="exportExcel">导出数据</el-button>
           </el-col>
           <el-col :span="4">
               <el-upload
                   class="clearfix"
                   action="http://localhost:9000/userEmp/importExcel"
                   name="file"
                   :on-progress="onExcelProgress"
                   :on-success="handleExcelSuccess"                   
                   accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                   multiple
                   :limit="1">
                <el-button  type="primary">数据导入</el-button>
               </el-upload>
         </el-col>
     </el-row>
</el-form-item>
      </el-form>
    </div>
    
    <!-- --------------------------------表格---------------------------------------- -->
  <el-table :data="userList" border style="width: 100%">
    <el-table-column align="center" prop="name" label="姓名" width="100"></el-table-column>
    <el-table-column align="center" prop="tel" label="电话" width="100"> </el-table-column>
    <el-table-column align="center" prop="sex" label="性别" width="100"></el-table-column>
    <el-table-column align="center" prop="add1" label="地址" width="100"></el-table-column>
    <el-table-column align="center" prop="pname" label="职位" width="100" >
    </el-table-column>
     <el-table-column align="center" prop="state" label="状态" width="100">
       <!-- 重要 -->
        <template slot-scope="scope">
          <div v-if="scope.row.state == 1">在职</div>
          <div v-if="scope.row.state == 2">离职</div>
        </template>
        <!-- 重要 -->
    </el-table-column>
   
    <el-table-column align="center" prop="date" label="注册日期" width="180"></el-table-column>
    <!-- 头像 -->
    <el-table-column label="头像" show-overflow-tooltip width="100">
        <template slot-scope="scope">
          <img :src="scope.row.beiyong1" style="width: 60px; height: 60px" />
        </template>
      </el-table-column>
    <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row.id)"
            >编辑</el-button
          >
          
          <el-popconfirm title="这是一段内容确定删除吗？" @confirm="handleDelete(scope.row.id)">
            <el-button
            slot="reference"
            size="mini"
            type="danger"           
            >删除</el-button>
          </el-popconfirm>
           
        </template>
      </el-table-column>
      
  </el-table>
  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.currentPage"
      :page-sizes="page.pageSizes"
      :page-size="query.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total">
    </el-pagination>
    <!-- --------------------------------添加---------------------------------------- -->
    <el-dialog title="添加客户" :visible.sync="dialog.addshow" width="50%">
      <el-form ref="addForm" :model="addForm" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
             <el-form-item label="电话" prop="tel">
              <el-input v-model="addForm.tel"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-radio size="small" v-model="addForm.sex" label="男">男</el-radio>
                <el-radio size="small" v-model="addForm.sex" label="女">女</el-radio>
            </el-form-item>

            <el-form-item label="地址" prop="add1">
              <el-input v-model="addForm.add1"></el-input>
            </el-form-item>
            <el-form-item label="账号" prop="account">
              <el-input v-model="addForm.account"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
             <el-form-item label="状态" prop="state">
                <el-radio size="small" v-model="addForm.state" :label="1">在职</el-radio>
                <el-radio size="small" v-model="addForm.state" :label="2">离职</el-radio>
            </el-form-item>
            <!-- 职位下拉框 -->
           <el-form-item label="职位" >
          <el-select v-model="addForm.deptId" placeholder="请选择职位">
            <el-option
              v-for="(dept, index) in deptList"
              :key="index"
              :label="dept.name"
              :value="dept.id"
            ></el-option>
          </el-select>
        </el-form-item>
          </el-col>
          <!-- 头像添加 -->
        <el-col :span="12">
            <el-form-item label="用户头像">
              <el-upload
                class="avatar-uploader"
                action="http://localhost:9000/userEmp/uploadoss"
                name="file"
                :show-file-list="false"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            
          </el-col>
           <!-- 头像添加结束 -->
        </el-row>
        
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.addshow = false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- --------------------------------修改---------------------------------------- -->
    <el-dialog title="修改员工" :visible.sync="dialog.updateshow" width="50%">
      <el-form ref="updateForm" :model="updateForm" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="updateForm.name"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="tel">
              <el-input v-model="updateForm.tel"></el-input>
            </el-form-item>
             <el-form-item label="账号" prop="account">
              <el-input v-model="updateForm.account"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="updateForm.password"></el-input>
            </el-form-item>         
            <el-form-item label="性别" prop="sex">
                <el-radio size="small" v-model="updateForm.sex" label="男">男</el-radio>
                <el-radio size="small" v-model="updateForm.sex" label="女">女</el-radio>
            </el-form-item>  
            <el-form-item label="状态" prop="state">
                <el-radio size="small" v-model="updateForm.state" :label="1">在职</el-radio>
                <el-radio size="small" v-model="updateForm.state" :label="2">离职</el-radio>
            </el-form-item>
             <!-- 职位下拉框 -->
           <el-form-item label="职位" >
          <el-select v-model="updateForm.deptId" placeholder="请选择职位">
            <el-option
              v-for="(dept, index) in deptList"
              :key="index"
              :label="dept.name"
              :value="dept.id"
            ></el-option>
          </el-select>
        </el-form-item>
            <!-- 授权 -->
            <!-- <el-form-item label="部门" prop="did">
              <el-select
                v-model="updateForm.deptId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in deptList"
                  :key="item.id"
                  :label="item.deptName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item> -->
          </el-col>
          <!-- 头像添加 -->
        <el-col :span="12">
            <el-form-item label="用户头像">
              <el-upload
                class="avatar-uploader"
                action="http://localhost:9000/userEmp/uploadoss"
                name="file"
                :show-file-list="false"
                :on-success="handleSuccess01"
                :before-upload="beforeUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
           <!-- 头像添加结束 -->

        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.updateshow = false">取 消</el-button>
        <el-button type="primary" @click="update()">确 定</el-button>
      </span>
    </el-dialog>
    </el-card>
</template>

<script>
export default {
  data() {
    return {
      uid: 0,
      checkList: [], //选中的角色
      roleList: [], //所有角色
      userList: [],// 所有员工
      deptList:[],// 所有职位
      imageUrl: "",// 图片路径
      page:{
        pageSizes:[5, 10, 20, 50, 100],
        total:0
      },
      query:{
        currentPage:1,
        pageSize:5,
        name:"",
        dateRange: [],
      },
      dialog:{
        addshow: false,
        updateshow:false,
        assingRolesVisible: false,
      },
      addForm: {

      },
      updateForm:{}, 
      rules: {
        name: [
          { required: true, message: '请输入客户姓名', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入客户电话', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请输入客户性别', trigger: 'blur' }
        ],
        add1: [
          { required: true, message: '请输入客户地址', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '请输入客户账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入客户密码', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请填写活动形式', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
     //文件上传成功的钩子函数
            handleExcelSuccess(res,result) {
                this.$message.success("导入成功");
                if (result.response.success) {
                    this.loadUsers();
                }
            },
            // 上传中
            onExcelProgress(){

            },
    // 查询所有职位
     selAllByDept() {
      this.$axios.get("http://localhost:9000/userEmp/selAllByPosition").then((res) => {
        this.deptList = res.data.data.positoinList;
      });
    },
    updateRole() {
      this.$axios
        .post("roles", {
          uid: this.uid,
          rids: this.checkList,
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success("授权成功");
            this.dialog.assingRolesVisible = false;
            this.checkList = [];
            this.uid = 0;
          }
        });
    },
    assignRole(id) {
      this.dialog.assingRolesVisible = true;
      this.$axios.get("/roles/" + id).then((res) => {
        this.uid = id;
        this.roleList = res.data.data.roleList;
        this.checkList = res.data.data.checkList;
      });
    },
    loadUsers(){
        this.$axios.post("http://localhost:9000/userEmp/selAll",this.query)
        .then(res=>{
            this.userList = res.data.data.userList;
            this.page.total = res.data.data.total;
        })
    },
    handleSizeChange(size) {      
      this.query.pageSize = size;
      this.loadUsers();
    },
    //当页数改变时
    handleCurrentChange(currentPage) {     
      this.query.currentPage = currentPage;
      this.loadUsers();
    },
    save() {
      this.$axios
        .post("http://localhost:9000/userEmp/", this.addForm)
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success("添加成功");
            this.dialog.addshow = false;
            this.loadUsers();
          } else {
            this.$message.error("出错了！请稍后重试");
          }
        })
        .then(() => {
          //注意要指定prop="did"属性才能起作用
          this.$refs.addForm.resetFields();
        });
    },
    // ===================数据导入导出===================
     exportExcel() {      
      this.$axios
        .post("http://localhost:9000/userEmp/excel", this.query,{responseType: 'blob'})
        .then((res) => {
          let fileName = res.headers["content-disposition"].split("=")[1];//得到后端生成的文件名          
          let url = window.URL.createObjectURL(new Blob([res.data]));
          let dom = document.createElement("a");
          dom.style.display = "none";
          dom.href = url;
          dom.setAttribute("download", fileName); //指定下载后的文件名，防跳转
          document.body.appendChild(dom);
          dom.click();
          // 释放内存
          dom.parentNode.removeChild(dom)
          window.URL.revokeObjectURL(dom.href);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    handleEdit(id) {
      
      this.$axios
        .get("http://localhost:9000/userEmp/" + id)
        .then((resp) => {
          this.updateForm = resp.data.data.user; 
        })
        .catch((error) => {
          this.$message.error("出错了,请稍后重试");
        });

      this.dialog.updateshow = true;
    },
    update() {
      this.$axios
        .put("http://localhost:9000/userEmp/", this.updateForm)
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success("操作成功");
            this.dialog.updateshow = false;
            this.loadUsers();
          } else {
            this.$message.error("操作失败");
          }
        })
        .catch((error) => {
          this.$message.error("出错了！请稍后重试");
        })
        .then(() => {
          this.$refs.updateForm.resetFields();
        });
    },
    // 上传图片方法
    handleSuccess(res, file) {
      if (res.code == 200) {
        this.imageUrl = res.message;
        this.addForm.beiyong1 = res.message; //将返回的文件储存路径赋值picture字段
        
      }
    },
    handleSuccess01(res, file) {
      if (res.code == 200) {
        this.imageUrl = res.message;
        this.updateForm.beiyong1 = res.message; //将返回的文件储存路径赋值picture字段
      }
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
     // 上传图片方法结束
    handleDelete(id) {
      this.$axios
        .delete("http://localhost:9000/userEmp/" + id)
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success("删除成功");
            this.loadUsers();
          } else {
            this.$message.success(res.data.message);
          }
        })
        .catch((error) => {
          this.$message.error("出错了！请稍后重试");
        });
    },
  },
  mounted(){
    this.loadUsers();
    this.selAllByDept();
  }
};
</script>
<style>
h1,
.box-card {
  margin: auto;
  width: 60%;
}

.el-form-item {
  margin-bottom: 0;
}

[v-cloak] {
  display: none;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>